﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using ODS.WebService.DeviceData;
using ODS.ViewModel;
using ODS.Model;
using ODS.Config;
using System.Diagnostics;
using ODS.Utils;
using System.Windows.Controls.Primitives;
using System.Windows.Media;

namespace ODS.UserControls
{
    public partial class MessageNotificationPage : UserControl
    {
        public bool IsShowingPopUp = false;

        public bool IsAllMessageTab = true;
        bool IsLoading = false;

        public PhoneApplicationPage ParentView;

        public MessageNotificationPage()
        {
            InitializeComponent();

            setAllMessageTab();
        }

        public void UnenableLongListSelecter()
        {
            MainLongListSelector.IsEnabled = false;
        }

        public void EnableLongListSelecter()
        {
            MainLongListSelector.IsEnabled = true;
        }

        void showWaiting()
        {
            if (ParentView.GetType() == typeof(DetailDevicePage))
            {
                DetailDevicePage detailPage = ParentView as DetailDevicePage;
                detailPage.showWaiting();
            }
            else if (ParentView.GetType() == typeof(TotalMessagePage))
            {
                TotalMessagePage totalMessagePage = ParentView as TotalMessagePage;
                //totalMessagePage.sh
            }
        }

        void hiddenWaiting()
        {
            if (ParentView.GetType() == typeof(DetailDevicePage))
            {
                DetailDevicePage detailPage = ParentView as DetailDevicePage;
                detailPage.hiddenWaiting();
            }
            else if (ParentView.GetType() == typeof(TotalMessagePage))
            {
                TotalMessagePage totalMessagePage = ParentView as TotalMessagePage;
                //totalMessagePage.sh
            }
        }

        void setAllMessageTab()
        {
            IsAllMessageTab = true;
            hlb_messageNumber.Background = new SolidColorBrush(Color.FromArgb(255, 255, 139, 0));
            hlb_unreadMessageNumber.Background = new SolidColorBrush(Colors.Transparent);
        }

        void setUnreadMessageTab()
        {
            IsAllMessageTab = false;
            hlb_unreadMessageNumber.Background = new SolidColorBrush(Color.FromArgb(255, 255, 139, 0));
            hlb_messageNumber.Background = new SolidColorBrush(Colors.Transparent);
        }
        #region event

        private async void hlb_totalMessage_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            hlb_messageNumber.IsEnabled = false;
            IsLoading = true;
            showWaiting();

            if (ParentView.GetType() == typeof(DetailDevicePage))
            {                
                 await App.MainViewModel.loadListMessagesOfCurrentDevice(App.currentDeviceModel, Constants.SIZE_PAGE, 0 );
            }
            else if (ParentView.GetType() == typeof(TotalMessagePage))
            {
                
            }

            hiddenWaiting();
            IsLoading = false;            
            hlb_messageNumber.IsEnabled = true;

            //IsAllMessageTab = true;
            setAllMessageTab();
        }

        private async void hlb_unreadMessage_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            hlb_unreadMessageNumber.IsEnabled = false;
            IsLoading = true;
            showWaiting();

            if (ParentView.GetType() == typeof(DetailDevicePage))
            {
                await App.MainViewModel.loadListUnreadMessagesOfCurrentDevice(App.currentDeviceModel, Constants.SIZE_PAGE, 0);
            }
            else if (ParentView.GetType() == typeof(TotalMessagePage))
            {
                
            }

            hiddenWaiting();
            IsLoading = false;
            hlb_unreadMessageNumber.IsEnabled = true;

            //IsAllMessageTab = false;
            setUnreadMessageTab();
        }

        private async void MainLongListSelector_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (MainLongListSelector.SelectedItem == null)
            {
                return;
            }

            MessageViewModel MessageVM = MainLongListSelector.SelectedItem as MessageViewModel;
            EventDetailModel eventDetail = MessageVM.EventDetailModel;

            String message = getMessageToShow(eventDetail);

            //tbl_message.Text = message;

            if (ParentView.GetType() == typeof(DetailDevicePage))
            {
                ((DetailDevicePage)ParentView).showPopUpWithAnimation(message);
            }
            else if (ParentView.GetType() == typeof(TotalMessagePage))
            {
                ((TotalMessagePage)ParentView).showPopUpWithAnimation(message);
            }

            MessageViewModel tempSelectedItem = MainLongListSelector.SelectedItem as MessageViewModel;
            MainLongListSelector.SelectedItem = null;

            if (eventDetail.ReadAt == null || eventDetail.ReadAt == DateTime.MinValue)
            {
                InfoResult result = await FlagDeviceEventAsReadService.FlagDeviceEventAsRead(eventDetail.EventId, eventDetail.DeviceIMEI);
                if (result.IsSuccess)
                {
                    if ((String)result.ReturnedObject == Constants.SUCCESS)
                    {
                        //unread message tab
                        if (!IsAllMessageTab)
                        {
                            MainLongListSelector.ItemsSource.Remove(tempSelectedItem);
                        }
                        else
                        {
                            tempSelectedItem.ReadAt = DateTime.Now;
                        }

                        //TotalMessageViewModel totalMessageVM = this.DataContext as TotalMessageViewModel;
                        //totalMessageVM.TotalUnreadMessage -= 1;
                        //if (totalMessageVM.TotalUnreadMessage < 0)
                        //    totalMessageVM.TotalUnreadMessage = 0;
                        await new WebBrowser().ClearCookiesAsync();

                        App.MainViewModel.getNumberUnreadMessage(eventDetail.DeviceIMEI);

                        App.MainViewModel.TotalMessageViewModel.TotalUnreadMessage -= 1;
                        if (App.MainViewModel.TotalMessageViewModel.TotalUnreadMessage < 0)
                            App.MainViewModel.TotalMessageViewModel.TotalUnreadMessage = 0;

                        
                    }
                    else
                    {
                        MessageBox.Show((String) result.ReturnedObject);
                    }
                }
                else
                {
                    MessageBox.Show(result.Error);
                }
            }
        }

        public String getMessageToShow(EventDetailModel eventDetail)
        {
            String message = "";


            switch (int.Parse(eventDetail.EventType))
            {
                case Constants.MONITOR_TYPE_HARSH_BRAKING:
                    message = FormatMessage(eventDetail, "Harsh Braking"); break; 
                case Constants.MONITOR_TYPE_HARSH_CORNERING:
                    message = FormatMessage(eventDetail, "Harsh Cornering"); break; 
                case Constants.MONITOR_TYPE_IMPACT:
                    message = FormatMessage(eventDetail, "Impact"); break; 
                case Constants.MONITOR_TYPE_IDLE:
                    message = FormatMessage(eventDetail, "Idling"); break; 
                case Constants.MONITOR_TYPE_GEOFENCE:
                    message = FormatMessage(eventDetail, "GeoFence"); break; 
                case Constants.MONITOR_TYPE_POWER:
                    message = FormatMessage(eventDetail, "Power low"); break; 
                case Constants.MONITOR_TYPE_SPEED:
                    message = FormatMessage(eventDetail, "Speeding"); break; 
                case Constants.MONITOR_TYPE_TOWING:
                    message = FormatMessage(eventDetail, "Towing"); break; 
                case Constants.EVENT_POSITION:
                    message = FormatMessage(eventDetail, "Vehicle is located"); break; 
                case Constants.REQUEST_COMMAND:
                    if (!String.IsNullOrEmpty(eventDetail.CommandType))
                    {
                        switch (int.Parse(eventDetail.CommandType))
                        {
                            case Constants.REQUEST_POSITION: message = String.Format("Request for location \nRegisterAt: {0}\n\n\n", eventDetail.RegisteredAt.ToString("dd MMM yyyy HH:mm tt")); break;
                            case Constants.BLAST_TRACKING: message = String.Format("Blast tracking \nRegisterAt: {0}\n\n\n", eventDetail.RegisteredAt.ToString("dd MMM yyyy HH:mm tt")); break;
                            case Constants.KILL_STARTER: message = String.Format("Kill starter \nRegisterAt: {0}\n\n\n", eventDetail.RegisteredAt.ToString("dd MMM yyyy HH:mm tt")); break;
                            case Constants.CANCEL_STATER: message = String.Format("Cancel starter kill \nRegisterAt: {0}\n\n\n", eventDetail.RegisteredAt.ToString("dd MMM yyyy HH:mm tt")); break;
                            case Constants.REBOOT_DEVICE: message = String.Format("Reboot device \nRegisterAt: {0}\n\n\n", eventDetail.RegisteredAt.ToString("dd MMM yyyy HH:mm tt")); break;
                            case Constants.SET_ODOMETOR: message = String.Format("Set odometer \nRegisterAt: {0}\n\n\n", eventDetail.RegisteredAt.ToString("dd MMM yyyy HH:mm tt")); break;
                        }; 
                    };break;
                case Constants.EVENT_MONITOR_PROCESS:
                    if (!String.IsNullOrEmpty(eventDetail.MonitorType))
                    {
                        switch (int.Parse(eventDetail.MonitorType))
                        {
                            case Constants.MONITOR_TYPE_HARSH_BRAKING:
                                message = "Monitor Harsh Braking processed\n\n\n"; break;
                            case Constants.MONITOR_TYPE_HARSH_CORNERING:
                                message = "Monitor Harsh Cornering processed\n\n\n"; break;
                            case Constants.MONITOR_TYPE_IMPACT:
                                message = "Monitor Impact processed\n\n\n"; break;
                            case Constants.MONITOR_TYPE_IDLE:
                                message = "Monitor Idling processed\n\n\n"; break;
                            case Constants.MONITOR_TYPE_GEOFENCE:
                                message = "Monitor Geofence processed\n\n\n"; break;
                            case Constants.MONITOR_TYPE_POWER:
                                message = "Monitor Power processed\n\n\n"; break;
                            case Constants.MONITOR_TYPE_SPEED:
                                message = "Monitor  Speeding processed\n\n\n"; break;
                            case Constants.MONITOR_TYPE_TOWING:
                                message = "Monitor Towing processed\n\n\n"; break;
                        }
                    }break;

            }

            return message;
        }

        String FormatMessage(EventDetailModel eventDetail, String header)
        {
            String message;
            if (eventDetail.MessageModel != null)
            {

                String heading = String.Format("Heading: {0}", eventDetail.MessageModel.Heading);
                String odemeter = String.Format("Odometer: {0} km", eventDetail.MessageModel.Odometer);
                String speed = String.Format("Speed: {0} km/h", eventDetail.MessageModel.Speed);
                String dateFormated = eventDetail.MessageModel.GeneratedAt.ToString("dd MMM yyyy HH:mm tt");
                String receDateFormat = eventDetail.MessageModel.ReceivedAt.ToString("dd MMM yyyy HH:mm tt");
                String generateAt = String.Format("GenerateAt: {0}", dateFormated);
                String receiveAt = String.Format("ReceiveAt: {0}", receDateFormat);
                message = String.Format("{0} at: \n    {1}\n{2}\n{3}\n{4}\n{5}\n{6}", header, eventDetail.MessageModel.Address,
                                                                                                     heading,
                                                                                                     speed,
                                                                                                     odemeter,
                                                                                                     generateAt,
                                                                                                     receiveAt);
            }
            else
            {
                String registerAt = String.Format("RegisterAt: {0}",eventDetail.RegisteredAt.ToString("dd MMM yyyy HH:mm tt"));
                message = String.Format("{0} at: \n{1} \n\n\n", header, registerAt);
            }
            return message;
        }

        private void LayoutRoot_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
           
        }

        private void MainLongListSelector_ItemRealized(object sender, Microsoft.Phone.Controls.ItemRealizationEventArgs e)
        {
            if (e.ItemKind == LongListSelectorItemKind.Item)
            {
                Debug.WriteLine("MainLongListSelector_ItemRealized");
                object o = e.Container.DataContext;
                items[o] = e.Container;
            }
        }

        private void MainLongListSelector_ItemUnrealized(object sender, Microsoft.Phone.Controls.ItemRealizationEventArgs e)
        {
            if (e.ItemKind == LongListSelectorItemKind.Item)
            {
                Debug.WriteLine("MainLongListSelector_ItemUnrealized");
                object o = e.Container.DataContext;
                items.Remove(o);
            }
        }

        private Dictionary<object, ContentPresenter> items = new Dictionary<object,ContentPresenter> ();

        private object GetFirstVisibleItem(LongListSelector lls)
        {
            var offset = FindViewport(lls).Viewport.Top;
            return items.Where(x => Canvas.GetTop(x.Value) + x.Value.ActualHeight > offset)
                .OrderBy(x => Canvas.GetTop(x.Value)).First().Key;
        }

        private static ViewportControl FindViewport(DependencyObject parent)
        {
            var childCount = VisualTreeHelper.GetChildrenCount(parent);
            for (var i = 0; i < childCount; i++)
            {
                var elt = VisualTreeHelper.GetChild(parent, i);
                if (elt is ViewportControl) return (ViewportControl)elt;
                var result = FindViewport(elt);
                if (result != null) return result;
            }
            return null;
        }

        private async void MainLongListSelector_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (!IsLoading)
            {
                int LengthItemSource = MainLongListSelector.ItemsSource.Count;
                int numberItemVisibleOnListView = getNumberVisibleInListView();

                //if too little item
                if (LengthItemSource < numberItemVisibleOnListView)
                    return;

                object obj = GetFirstVisibleItem(MainLongListSelector);
                int indexFirstVisibleItem = MainLongListSelector.ItemsSource.IndexOf(obj);
               
                if (indexFirstVisibleItem + numberItemVisibleOnListView >= LengthItemSource -1)
                {
                    IsLoading = true;
                    showWaiting();
                    if (IsAllMessageTab)
                    {
                        if (ParentView.GetType() == typeof(DetailDevicePage))
                        {
                            await App.MainViewModel.loadListMessagesOfCurrentDevice(App.currentDeviceModel, Constants.SIZE_PAGE, LengthItemSource);
                        }
                        else if (ParentView.GetType() == typeof(TotalMessagePage))
                        {

                        }
                    }
                    else
                    {
                        if (ParentView.GetType() == typeof(DetailDevicePage))
                        {
                            await App.MainViewModel.loadListUnreadMessagesOfCurrentDevice(App.currentDeviceModel, Constants.SIZE_PAGE, LengthItemSource);
                        }
                        else if (ParentView.GetType() == typeof(TotalMessagePage))
                        {

                        }
                    }
                    hiddenWaiting();
                    IsLoading = false;
                }
            }
        }

        int getNumberVisibleInListView()
        {
            if (ParentView.GetType() == typeof(DetailDevicePage))
            {
                //cheat
                return 6;
            }
            else if (ParentView.GetType() == typeof(TotalMessagePage))
            {
                return 8;
            }
            else
            {
                //implement here
                throw new Exception();
            }
            
        }




        #endregion
    }
}
